import {
  Body,
  Controller,
  Post,
  UploadedFile,
  UploadedFiles,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { ApiProperty, ApiTags } from '@nestjs/swagger';
import { createWriteStream } from 'fs';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
@Controller('upload')
@ApiTags('文件上传')
export class UploadController {
  //   这是上传单个文件的处理方式
  // 文件上传 , 该方法可以上传图片或者是文件夹，如果有需要，可以对文件的后缀名进行处理，限定上传的内容
  @Post('doAdd')
  @UseInterceptors(FileInterceptor('file'))
  @ApiProperty({ description: '上传文件' })
  doAdd(@Body() body, @UploadedFile() file) {
    const timestamp = uuidv4();
    // 定义文件存放的路径和名称
    const writeStream = createWriteStream(
      join(
        __dirname,
        '../../public/uploadAvatar',
        `${timestamp}-${file.originalname}`,
      ),
    );

    // 在定义的路径下写入流
    writeStream.write(file.buffer);
    return {
      msg: '上传图片成功',
      url: `/vehicle/uploadAvatar/${timestamp}-${file.originalname}`,
    };
  }

  // 上传多张车辆图片
  @Post('doAdds_car')
  @UseInterceptors(FilesInterceptor('files'))
  doAddsCar(@Body() body, @UploadedFiles() files) {
    const timestamp = uuidv4();

    // console.log(body);
    // console.log(file); // 文件将是一个数组
    // 如果要实现图片上传的话还需要进行一些判断

    const urlList = [];

    for (const file of files) {
      urlList.push({
        url: `/vehicle/uploadCarPhoto/${timestamp}-${file.originalname}`,
      });

      const writeImage = createWriteStream(
        join(
          __dirname,
          '../../public/uploadCarPhoto',
          `${timestamp}-${file.originalname}`,
        ),
      );
      writeImage.write(file.buffer);
    }

    return {
      msg: '上传图片成功',
      list: urlList,
    };
  }

  // 上传多张服务图片
  @Post('doAdds_service')
  @UseInterceptors(FilesInterceptor('files'))
  doAddsService(@Body() body, @UploadedFiles() files) {
    const timestamp = uuidv4();

    const urlList = [];

    for (const file of files) {
      urlList.push({
        url: `/vehicle/uploadServicePhoto/${timestamp}-${file.originalname}`,
      });

      const writeImage = createWriteStream(
        join(
          __dirname,
          '../../public/uploadServicePhoto',
          `${timestamp}-${file.originalname}`,
        ),
      );
      writeImage.write(file.buffer);
    }
    return {
      msg: '上传图片成功',
      list: urlList,
    };
  }
}
